package customer

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/ossfile"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/customer"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/file"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/remote/bigdata_remote"
	pb "git.mycaigou.com/gfyx/micro-gfyx-user-service/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
	"git.myscrm.cn/golang/stark/v4"
	"time"
)

type customerGroupService struct {
	customerGroupRepository customer.CustomerGroupRepositoryIface
	commonFile              file.CommonFileRepoIface
	bigDataRepo             bigdata_remote.BigDataServiceRepositoryIface
}

func NewCustomerGroupService(
	customerGroupRepository customer.CustomerGroupRepositoryIface,
	commonFile file.CommonFileRepoIface,
	bigDataRepo bigdata_remote.BigDataServiceRepositoryIface,
) CustomerGroupServiceIface {
	return &customerGroupService{
		customerGroupRepository: customerGroupRepository,
		commonFile:              commonFile,
		bigDataRepo:             bigDataRepo,
	}
}

// List 获取战图列表
func (s *customerGroupService) List(ctx context.Context, request *pb.GetCustomerGroupListRequest) (*pb.GetCustomerGroupListResponse, error) {
	// 构造查询参数
	condition := make(map[string]interface{})
	if request.Status > 0 {
		condition["c.status"] = request.Status
	}
	// 租户 code 特殊处理下
	if request.TenantCode != "" {
		condition["tenant_code_with_others"] = request.TenantCode
	}
	pageInfo := &utils.PageInfo{Page: int(request.Page), PageSize: int(request.PageSize)}
	total, list, err := s.customerGroupRepository.QueryCustomerGroupList(ctx, condition, pageInfo, "c.created_on desc")
	if err != nil {
		return nil, err
	}
	var customerGroupList []*pb.CustomerGroupListItem
	for _, v := range list {
		tempUrl := ""
		if v.FilePath != "" {
			tempUrl, _ = ossfile.GetSignURL(v.FilePath)
		}
		customerGroupList = append(customerGroupList, &pb.CustomerGroupListItem{
			Id:          v.Id,
			Title:       v.Title,
			FileId:      v.FileId,
			FileUrl:     tempUrl,
			CreatedBy:   v.CreatedBy,
			TenantCodes: v.TenantCodes,
			CreatedOn:   v.CreatedOn.Format("2006-01-02 15:04:05"),
			Status:      v.Status,
			IsPublic:    v.IsPublic,
			Total:       v.Total,
		})
	}

	return &pb.GetCustomerGroupListResponse{Total: int32(total), List: customerGroupList}, nil
}

func (s *customerGroupService) Save(ctx context.Context, request *pb.SaveCustomerGroupRequest) (*pb.SaveCustomerGroupResponse, error) {
	// 标题不能重复
	isRepeat, _ := s.customerGroupRepository.IsRepeatTitle(ctx, request.Title, request.Id)
	if isRepeat {
		return nil, errors.New("标题:" + request.Title + "重复，请更换标题名称")
	}
	po := &customer.CustomerGroupPo{}
	if request.Id != 0 {
		po.ID = request.Id
	} else {
		po.CreatedBy = request.CreatedBy
		po.CreatedOn = time.Now()
	}
	po.Title = request.Title
	po.CommonFileUid = request.FileId
	po.LandTitle = request.LandTitle
	po.LandTitleOp = request.LandTitleOp
	po.LandUsage = request.LandUsage
	po.LandUsageOp = request.LandUsageOp
	po.BuildingType = request.BuildingType
	po.BuildingTypeOp = request.BuildingTypeOp
	po.BuildingTitle = request.BuildingTitle
	po.BuildingTitleOp = request.BuildingTitleOp
	po.BidTitle = request.BidTitle
	po.BidTitleOp = request.BidTitleOp
	po.WinBidTitle = request.WinbidTitle
	po.WinBidTitleOp = request.WinbidTitleOp
	po.IsPublic = request.IsPublic
	po.ModifiedBy = request.CreatedBy
	po.ModifiedOn = time.Now()
	customerGroupPo, err := s.customerGroupRepository.SaveCustomerGroup(ctx, po)
	if err != nil {
		stark.Logger.Errorf(ctx, "SaveCustomerGroup failed, err:%v", err)
		return nil, err
	}
	err = s.customerGroupRepository.SaveCustomerGroupTenantRelation(ctx, customerGroupPo, request.TenantCodes)
	if err != nil {
		stark.Logger.Errorf(ctx, "SaveCustomerGroupTenantRelation failed, err:%v", err)
		return nil, err
	}
	return &pb.SaveCustomerGroupResponse{Id: customerGroupPo.ID}, nil
}

func (s *customerGroupService) Detail(ctx context.Context, request *pb.GetCustomerGroupDetailRequest) (*pb.GetCustomerGroupDetailResponse, error) {
	detail, err := s.customerGroupRepository.GetCustomerGroupDetail(ctx, request.Id)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetCustomerGroupDetail failed, err:%v", err)
		return nil, err
	}
	// 获取基本信息
	responseData := &pb.GetCustomerGroupDetailResponse{
		Id:              detail.ID,
		Title:           detail.Title,
		IsPublic:        detail.IsPublic,
		LandUsage:       detail.LandUsage,
		LandUsageOp:     detail.LandUsageOp,
		LandTitle:       detail.LandTitle,
		LandTitleOp:     detail.LandTitleOp,
		BuildingType:    detail.BuildingType,
		BuildingTypeOp:  detail.BuildingTypeOp,
		BuildingTitle:   detail.BuildingTitle,
		BuildingTitleOp: detail.BuildingTitleOp,
		BidTitle:        detail.BidTitle,
		BidTitleOp:      detail.BidTitleOp,
		WinbidTitle:     detail.WinBidTitle,
		WinbidTitleOp:   detail.WinBidTitleOp,
		Status:          detail.Status,
		FileId:          detail.CommonFileUid,
	}

	// 获取租户信息
	tenantCodes, err := s.customerGroupRepository.GetCustomerGroupTenantRelation(ctx, request.Id)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetCustomerGroupTenantRelation failed, err:%v", err)
		return nil, err
	}
	responseData.TenantCodes = tenantCodes

	// 获取文件信息
	fileInfo, err := s.commonFile.QueryByUid(ctx, detail.CommonFileUid)
	if err == nil && fileInfo != nil {
		responseData.FileUrl, _ = ossfile.GetSignURL(fileInfo.FilePath)
	}

	return responseData, nil
}

func (s *customerGroupService) Delete(ctx context.Context, request *pb.DeleteCustomerGroupRequest) (*pb.DeleteCustomerGroupResponse, error) {
	err := s.customerGroupRepository.DeleteCustomerGroup(ctx, request.Id)
	if err != nil {
		stark.Logger.Errorf(ctx, "DeleteCustomerGroup failed, err:%v", err)
		return nil, err
	}
	return &pb.DeleteCustomerGroupResponse{
		AffectRows: 1,
	}, nil
}

func (s *customerGroupService) SyncCustomerGroupTotal(ctx context.Context) error {
	ids, err := s.customerGroupRepository.GetAllCustomerGroupIds(ctx)
	if err != nil {
		return err
	}

	if len(ids) == 0 {
		return nil
	}

	for _, id := range ids {
		total, err := s.bigDataRepo.GetCustomerGroupCount(ctx, id)
		if err != nil {
			stark.Logger.Errorf(ctx, "GetCustomerGroupCount failed,id:%d, err:%v", id, err)
			continue
		}
		if total > 0 {
			err = s.customerGroupRepository.UpdateCustomerGroupTotalById(ctx, id, total)
			if err != nil {
				stark.Logger.Errorf(ctx, "UpdateCustomerGroupTotalById failed,id:%d, err:%v", id, err)
			}
		}
	}

	return nil
}
